<template>
  <div class="page-container">
    <!-- 内容区居中，左右留空 -->
    <div class="content-wrapper">
      <!-- 头部用户信息区域 -->
      <div class="header-user-info">
        <div class="user-profile">
          <!-- 头像上传区域（使用Element UI标准样式） -->
          <div class="user-avatar">
            <el-upload
                class="avatar-uploader"
                action="http://localhost:5080/changepictrue"
                :data="{email:userEmail}"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :on-error="handleAvatarError"
                :before-upload="beforeAvatarUpload"
                :headers="{'token': token}"
            >
              <!-- 修改：添加alt属性描述图片，使用默认头像或后端返回的头像 -->
              <img v-if="userAvatar" :src="avatarUrl||'/default.jpg'" class="avatar" alt="用户头像" @error="handleImageError">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>

          <!-- 用户信息区域 -->
          <div class="user-details">
            <!-- 用户名修改区域（带修改/确认/取消按钮） -->
            <div class="user-name-container">
              <el-input
                  v-model="userName"
                  placeholder=""
                  :disabled="!isEditingName"
                  class="username-input"
                  @keyup.enter.native="handleConfirmName"
              />

              <!-- 操作按钮组 -->
              <div class="name-action-buttons">
                <el-button
                    v-if="!isEditingName"
                    type="text"
                    @click="isEditingName = true"
                    class="edit-btn"
                >
                  修改
                </el-button>

                <div v-if="isEditingName" class="confirm-buttons">
                  <el-button type="text" @click="cancelEditName">取消</el-button>
                  <el-button type="text" @click="handleConfirmName" class="confirm-btn">确认</el-button>
                </div>
              </div>
            </div>

            <!-- 邮箱信息 -->
            <div class="user-email">{{ userEmail }}</div>

            <!-- 修改密码入口 -->
            <div class="change-password" @click="openChangePasswordDialog">修改密码</div>
          </div>
        </div>
      </div>

      <!-- 头像上传加载提示 -->
      <el-dialog v-model="avatarLoading" title="提示" width="30%" center>
        <span>头像上传中，请稍候...</span>
      </el-dialog>

      <!-- 修改密码对话框 -->
      <el-dialog :visible.sync="changePasswordDialogVisible" title="修改密码" width="40%" :modal="false">
        <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="140px">
          <el-form-item label="当前密码" prop="oldPassword">
            <el-input v-model="passwordForm.oldPassword" type="password" show-password size="large"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="passwordForm.newPassword" type="password" show-password size="large"></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input v-model="passwordForm.confirmPassword" type="password" show-password size="large"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="changePasswordDialogVisible = false" size="large">取 消</el-button>
            <el-button type="primary" @click="submitPasswordForm" size="large">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import service from '@/utils/request';
import router from '@/router';
export default {
  name: 'UserProfile',
  data() {
    return {
      // 基础状态
      changePasswordDialogVisible: false,
      avatarLoading: false,
      isEditingName: false,  // 用户名是否处于编辑状态
      originalName: '',      // 保存原始用户名（用于取消编辑时恢复）
      uploadUrl: '',
      // 表单数据
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      userName: '',
      passwordRules: {},
      userData: JSON.parse(localStorage.getItem('userData'))|| {}
    };
  },
  computed: {
    token() {
      return this.userData.token || '';
    },
    user() {
      return this.$store.state.userData || {};
    },
    avatarUrl(){
      const email = this.$store.state.userData?.email;
      return "/"+email+".jpg";
    },
    // 头像地址
    userAvatar() {
      // 如果后端返回的是本地路径，使用默认头像
      if (this.userData.avatar && this.userData.avatar.startsWith('D:/')) {
        return 'https://picsum.photos/200/200?random=user';
      }
      return this.userData.avatar || 'https://picsum.photos/200/200?random=default';
    },
    // 邮箱地址
    userEmail() {
      return this.userData.email || '未绑定邮箱';
    }
  },
  watch: {
    // 监听用户信息变化，同步更新用户名
    userData(newVal) {
      this.userName = newVal.username || "用户";
    }
  },
  created() {
    // 初始化用户名
    this.userName = this.userData.username || '用户';
    console.log("初始化后的用户名：", this.userName);
    this.originalName = this.userName;

    // 初始化密码验证规则
    this.passwordRules = {
      oldPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value === this.passwordForm.oldPassword) {
              callback(new Error('新密码不能与当前密码相同'));
            } else {
              callback();
            }
          }, trigger: 'blur'
        }
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== this.passwordForm.newPassword) {
              callback(new Error('两次输入的密码不一致'));
            } else {
              callback();
            }
          }, trigger: 'blur'
        }
      ]
    };
  },
  methods: {
    handleImageError(event) {
      // 图片加载失败时将src设置为null或默认图片
      // 或者使用默认图片：
      event.target.src = '/default.jpg';
    },
    // 头像上传相关方法
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像只能是 JPG 或 PNG 格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传头像大小不能超过 2MB!');
        return false;
      }

      // 显示加载状态
      this.avatarLoading = true;
      return true;
    },
    handleAvatarSuccess(response, file, fileList) {
      this.avatarLoading = false;
      if (response.code === 200) {
        this.$message.success('头像上传成功');
        this.userData.avatar = response.data.avatarUrl;
        localStorage.setItem('userData', JSON.stringify(this.userData));
      } else {
        this.$message.error('头像上传失败：' + (response.msg || '未知错误'));
      }
    },
    handleAvatarError(err) {
      this.avatarLoading = false;
      console.error('头像上传错误:', err);
      // 显示错误信息
      if (err.response) {
        // 服务器返回错误状态码
        this.$message.error(`上传失败: ${err.response.status} ${err.response.statusText}`);
      } else if (err.message) {
        // 网络错误或其他错误
        this.$message.error(`上传失败: ${err.message}`);
      } else {
        this.$message.error('上传失败，未知错误');
      }
    },
    // 用户名修改相关方法
    cancelEditName() {
      // 取消修改，恢复原始用户名
      this.userName = this.originalName;
      this.isEditingName = false;
    },

    async handleConfirmName() {
      // 验证用户名不为空
      if (!this.userName.trim()) {
        this.$message.error('用户名不能为空');
        return;
      }

      // 用户名未修改时直接关闭编辑状态
      if (this.userName === this.originalName) {
        this.isEditingName = false;
        return;
      }

      try {
        const email = this.$store.state.userData?.email;
        //后端修改用户名
        const response = await service.post('/update-username',
            {email:email,
              username:this.userName
            });
        const Result = Array.isArray(response.data) ? response.data[0] : response.data;
        this.userData.username = this.userName;
        localStorage.setItem('userData', JSON.stringify(this.userData));
        // 更新Vuex状态
        this.$store.dispatch('user/updateUserItem', {
          username: this.userName
        });
        //console.log(this.username);
        //前端测试
        //const response = await service.post('/update-username', {email });
          this.$message.success('用户名修改成功');

          // 更新localStorage
          this.isEditingName = false; // 只在成功时关闭编辑状态
      } catch (error) {
        console.error('请求错误:', error);
        this.$message.error('网络错误，修改失败');
      }
    },

    // 修改密码相关方法
    openChangePasswordDialog() {
      this.passwordForm = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      };
      this.changePasswordDialogVisible = true;
    },

    async submitPasswordForm() {
      this.$refs.passwordFormRef.validate(async (valid) => {
        if (!valid) return;

        if (this.passwordForm.newPassword !== this.passwordForm.confirmPassword) {
          this.$message.error('两次输入的新密码不一致');
          return;
        }

        try {
          // 调用修改密码接口
          const response = await service.post('/update-password', {
                email: this.userEmail,
                newpassword: this.passwordForm.newPassword
              }
          );
            this.$message.success('密码修改成功，请重新登录');
            this.changePasswordDialogVisible = false;

            // 直接清除localStorage中的用户数据，不依赖Vuex
            localStorage.removeItem('userData');

            // 直接跳转登录页，不依赖Vuex action
            router.push('/login');
        } catch (error) {
          this.$message.error(error.response?.data?.msg || '修改密码失败');
        }
      });
    }
  }
}
</script>

<style scoped>
/* 页面容器样式（左右留空） */
.page-container {
  width: 100%;
  padding: 40px 0;
  background-color: #f9f9f9;  /* 页面背景色 */
}

/* 内容包裹器（居中显示，限制最大宽度） */
.content-wrapper {
  width: 100%;
  max-width: 800px;  /* 内容最大宽度，左右自动留空 */
  margin: 0 auto;
  padding: 0 20px;
}

/* 头部用户信息区域 */
.header-user-info {
  padding: 30px 0;
}

.user-profile {
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 头像上传样式（Element UI标准样式） */
.user-avatar {
  margin-bottom: 30px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

/* 用户信息区域 */
.user-details {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

/* 用户名容器（带修改按钮） */
.user-name-container {
  display: flex;
  align-items: center;
  width: 100%;
  max-width: 400px;
  margin-bottom: 15px;
}

.username-input {
  flex: 1;
  text-align: center;
  font-size: 24px;
}

/* 用户名操作按钮 */
.name-action-buttons {
  margin-left: 10px;
}

.edit-btn {
  color: #409EFF;
}

.confirm-buttons {
  display: flex;
  gap: 10px;
}

.confirm-btn {
  color: #409EFF;
  font-weight: 500;
}

/* 邮箱样式 */
.user-email {
  font-size: 16px;
  color: #606266;
  margin-bottom: 20px;
}

/* 修改密码链接 */
.change-password {
  font-size: 14px;
  color: #409EFF;
  cursor: pointer;
  transition: color 0.2s;
}

.change-password:hover {
  color: #66b1ff;
  text-decoration: underline;
}

/* 表单样式 */
.el-form {
  width: 100%;
}

.el-form-item {
  margin-bottom: 24px;
}

.el-dialog__header {
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.el-dialog__footer {
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .avatar-uploader .el-upload {
    width: 140px;
    height: 140px;
  }

  .avatar-uploader-icon {
    width: 140px;
    height: 140px;
    line-height: 140px;
  }

  .avatar {
    width: 140px;
    height: 140px;
  }

  .username-input {
    font-size: 20px;
  }
}
</style>